﻿using System;

namespace BusinessLayer
{
    public static class ObjectExtensions
    {

        public static T With<T>(this T with, Action<T> action)
        {
            if (with != null)
            {
                action(with);
            }
            return with;
        }

        public static T ChangeTypeTo<T>(this object value)
        {
            if (value == null || value is DBNull) return default(T);
            //If the value is empty
            if (value.ToString() == string.Empty) return default(T);
            var type = typeof(T);
            return (T)Convert.ChangeType(value, type.IsGenericType ? Nullable.GetUnderlyingType(type) : type);
        }

        public static void TryDispose(this object obj)
        {
            var disposable = obj as IDisposable;
            if (disposable == null) return;
            try
            {
                disposable.Dispose();
            }
            catch { }
        }

        public static bool IsTypeOf<T>(this object value)
        {
            //if(value == null || value is DBNull)
            //    return typeof(T) == typeof(Nullable);
            //return null != value.ChangeTypeTo<T>();
            return value is T;
        }

        public static T ConvertTo<T>(this object value,
                 bool isThrowException = false,
              T defaultValue = default(T))
        {
            if (value is T)
            {
                return (T)value;
            }
            else
            {
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch (Exception ex)
                {
                    if (isThrowException)
                    {
                        throw ex;
                    }
                }
            }
            return defaultValue;
        }
    }
}
